import { shell, BrowserWindow, WebContentsView, screen } from 'electron'
import icon from '../../../resources/icon.png?asset'
import { is } from '@electron-toolkit/utils'
import { join } from 'path'
import BaseWindow from './components/BaseWindow'

export default class AiChatWindow extends BaseWindow {
  initialX = 0
  initialY = 0
  winW = 0
  winH = 0
  //创建窗口
  create(): void {
    if (this.frame !== null && !this.frame.isDestroyed()) return
    this.frame = new BrowserWindow({
      width: 300,
      height: 440,
      show: false, // 创建时窗口不显示
      frame: false,
      alwaysOnTop: true, // 窗口置顶 默认值为false
      autoHideMenuBar: true, // 隐藏菜单栏 默认值为false
      hasShadow: false, // 禁止窗口阴影 默认值为true
      skipTaskbar: true, // 隐藏任务栏 默认值为false
      minWidth: 300,
      minHeight: 440,
      icon,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false, // 禁用沙箱模式
        zoomFactor: 1.0 // 禁止缩放
      }
    })

    this.frame!.on('blur', () => {
      this.frame!.hide()
      this.showAiIconWindow()
    })

    const view = new WebContentsView()
    this.frame.contentView.addChildView(view)

    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      view.webContents.loadURL('https://www.baidu.com/?tn=15007414_20_dg')
    } else {
      // view.webContents.loadURL('https://yst.woa.com/chat/chatComp?web_key=1718799630_4115_hallong&hide_header=0')
      view.webContents.loadURL('https://knot.woa.com/chat?web_key=1c2a6b4568f24e00a58999c1b7cb0f6e&hidenav=1')
    }

    view.setBounds({ x: 0, y: 40, width: 300, height: 400 })

    // 拦截页面中的 window.open() 和 target="_blank" 链接
    view.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url) // 使用系统默认浏览器打开
      return { action: 'deny' }       // 阻止在 Electron 内部新建窗口
    })

    // 设置窗口打开链接的处理方式
    this.frame.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    const routerPath = '/aiChatFrameHead'
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath)
    } else {
      this.frame.loadFile(join(__dirname, '../renderer/index.html'), {
        hash: routerPath
      })
    }

    this.frame.on('resize', () => {
      const [width, height] = this.frame!.getSize() // 获取当前窗口内容区域大小
      view.setBounds({
        x: 0,
        y: 40,
        width: width,
        height: height - 40 // 预留顶部 40px
      })
    })
  }

  // 拖拽相关
  startDrag () {
    const point = screen.getCursorScreenPoint()
    const bounds = this.frame!.getContentBounds()
    this.initialX = point.x - bounds.x
    this.initialY = point.y - bounds.y
    this.winW = bounds.width
    this.winH = bounds.height
  }
  moveDrag(): void {
    const point = screen.getCursorScreenPoint() // 获取当前鼠标位置
    let x = point.x - this.initialX
    let y = point.y - this.initialY
    this.frame?.setBounds({ x, y, width: this.winW, height: this.winH })
  }
  stopDrag () {

  }

  showAiChat (x, y) {
    // 计算所有屏幕组成的大矩形区域
    const allDisplays = screen.getAllDisplays()
    let screenBounds = allDisplays.reduce((acc, display) => {
      const bounds = display.bounds
      acc.minX = Math.min(acc.minX, bounds.x)
      acc.maxX = Math.max(acc.maxX, bounds.x + bounds.width)
      acc.minY = Math.min(acc.minY, bounds.y)
      acc.maxY = Math.max(acc.maxY, bounds.y + bounds.height)
      return acc
    }, {
      minX: Infinity,
      maxX: -Infinity,
      minY: Infinity,
      maxY: -Infinity,
    })

    // 获取当前鼠标所在屏幕
    const currentDisplay = screen.getDisplayNearestPoint({ x, y })
    const workArea = currentDisplay.workArea

    const mouseRange = { minX: 0, maxX: 0, minY: 0, maxY: 0}
    mouseRange.minX = screenBounds.minX // 最小X坐标向左偏移68像素
    mouseRange.maxX = screenBounds.maxX // 最大X坐标向右偏移68像素
    mouseRange.minY = workArea.y // 最大X坐标向右偏移68像素
    mouseRange.maxY = workArea.height + workArea.y // 最大X坐标向右偏移68像素

    const [winW, winH] = this.frame!.getSize() // 获取窗口的宽度和高度
    if (x < mouseRange.minX) x = mouseRange.minX
    if (x + winW > mouseRange.maxX) x = mouseRange.maxX - winW

    if (y < mouseRange.minY) y = mouseRange.minY
    if (y + winH > mouseRange.maxY) y = mouseRange.maxY - winH

    this.frame?.setPosition(x, y)
  }

  showAiIconWindow () {
    const aiIconWindow = this.getWindow('aiIconWindow')
    aiIconWindow.show()
  }
}
